package a12_SeqList.LinkedQueue;

import java.util.NoSuchElementException;

/**
 * @Author quan
 * @Description 底层用链表来实现队列接口
 * @Date 2023/3/22 19:29
 */
public class MyQueue<E> implements Queue<E> {
    private Node head;
    private Node tail;
    private int size;
    class Node{
        E val;
        Node next;
        public Node(E val) {
            this.val = val;
        }
    }
    /**
     * /入队列：链表的尾插
     */
    @Override
    public void offer(E element) {
        //产生新节点
        Node node = new Node(element);
        //如果链表为空，此时新节点就是头和尾
        if(head==null){
            head = tail = node;
        }
        //如果链表不为空，此时
        tail.next = node;
        tail = node;
        size++;
    }
    /**
     * /出队列：出的是链表中的头结点
     */
    @Override
    public E poll() {
        E val = head.val;
        head = head.next;
        size--;
        return val;
    }
    /**
     * 查看队首元素
     */
    @Override
    public E peek() {
        if (size == 0) {
            throw new NoSuchElementException("queue is empty!cannot peek");
        }
        return head.val;
    }
    /**
     * 重写ToString方法
     */
    @Override
    public String toString() {
        //遍历链表
        StringBuilder sb = new StringBuilder();
        sb.append("front[");
        for (Node x = head; x !=null; x=x.next) {
            sb.append(x.val);
            if(x.next != null){
                sb.append(", ");
            }
        }
        sb.append("]tail");
        return sb.toString();
    }
}
